import { message } from 'antd'
import { useEffect, useRef } from 'react'
import css from './index.module.less'
import { useNavigate } from 'react-router-dom'
import { z } from 'zod'

export default function Index() {
  const ref = useRef<HTMLFormElement>(null)
  const nav = useNavigate()
  const token = localStorage.getItem('PROJECT_TOKEN')
  useEffect(() => {
    if (token) {
      nav('/')
    }
  }, [])

  const myschema = z.object({
    username: z.string().min(1, '用户名不能为空'),
    password: z.string().min(1, '密码不能为空')
  })

  const login = () => {
    const data = {
      username: ref.current?.username.value,
      password: ref.current?.password.value
    }
    try {
      myschema.parse(data)
      console.log(data)
      if (data.username === 'admin' && data.password === '123') {
        message.success('登录成功')
        window.location.href = '/'
        localStorage.setItem('PROJECT_TOKEN', '123')
      } else {
        message.error('用户名或密码错误')
      }
    } catch (err) {
      console.log('🚀 ~ login ~ err:', err)
      const message = err as any
      console.log(message)

      // console.log(message.);
    }
  }

  return (
    <div className={css['login-box']}>
      <h2>Login</h2>
      <form id="myForm" ref={ref}>
        <div className={css['user-box']}>
          <input type="text" name="username" required={true} />
          <label>Username</label>
        </div>
        <div className={css['user-box']}>
          <input type="password" name="password" required={true} />
          <label>Password</label>
        </div>
        <a target="_blank" onClick={login} style={{ cursor: 'pointer' }}>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          登录
        </a>
      </form>
    </div>
  )
}
